//
//  KLSGLiveWebViewController.m
//  KaoLaShiGuangFM
//
//  Created by lanou3g on 15/10/27.
//  Copyright © 2015年 com.lanou3g. All rights reserved.
//

#import "KLSGLiveWebViewController.h"
#import "KLSGRadioTableViewCell.h"
#import "KLSGRadioModel.h"
#import "KLSGRadioListViewController.h"
#import "KLSGCityListViewController.h"
#import "KLSGPlayRadioViewController.h"
#import "KLSGDataFail.h"

@interface KLSGLiveWebViewController ()<UITableViewDataSource, UITableViewDelegate>
//
@property (nonatomic, strong) KLSGDataFail *dataFailView;
// tableView
@property (nonatomic, strong) UITableView *tableView;
// 声明数组属性,存放model
@property (nonatomic, strong) NSMutableArray *allDataArray;

// 判断数据加载情况
@property (nonatomic, assign) BOOL datasucceed;

@end

@implementation KLSGLiveWebViewController

- (void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = NO;

    if (self.allDataArray.count == 0) {
        [self setUpData];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 不计算导航栏高度
    self.edgesForExtendedLayout = UIRectEdgeNone;
    // 1.创建布局
    [self addSubViews];
    
    [self setupRefresh];
}

#pragma mark - 下拉刷新
- (void)setupRefresh
{
    [self.tableView addHeaderWithTarget:self action:@selector(headerRefreshing)];
    [self.tableView headerBeginRefreshing];
    self.tableView.headerPullToRefreshText = @"下拉可以刷新";
    self.tableView.headerRefreshingText = @"正在加载";
    self.tableView.headerReleaseToRefreshText = @"松开马上刷新";
    
}
- (void)headerRefreshing
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self setUpData];
        [self.tableView headerEndRefreshing];
    });
}

#pragma mark - 解析数据
- (void)setUpData
{
    [_dataFailView hidden];
    // 1.创建session对象  NSURLSession
    NSURLSession *session = [NSURLSession sharedSession];
    // 2.创建网址对象
    NSURL *url = [NSURL URLWithString:kRadioAPI];
    // 3.根据URL创建请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    // 4.建立会话 NSURLSessionDataTask
    // block中要使用self 需要用__block修饰一下
    __block KLSGLiveWebViewController *mySelf = self;
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        // 5.解析
        if (data != nil) {
            NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
            // 取出需要的数据
            NSArray *resultArray = dic[@"result"];
            
            // 初始化数组
            mySelf.allDataArray = [NSMutableArray array];
            // 遍历数组给model赋值,并保存到数组中
            for (NSDictionary *dic in resultArray) {
                KLSGRadioModel *model = [[KLSGRadioModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [mySelf.allDataArray addObject:model];
            }
            
            // 回到主线程刷新
            [mySelf performSelectorOnMainThread:@selector(reloadData:) withObject:self.tableView waitUntilDone:YES];
            
        } else {
            [mySelf performSelectorOnMainThread:@selector(failAction) withObject:nil waitUntilDone:YES];
        }
        
    }];
    
    // 6.启动解析
    [task resume];
    
}

#pragma mark - 重新加载数据
- (void)failAction
{
    self.dataFailView = [[KLSGDataFail alloc] initWithFrame:CGRectMake(0, kScreenHeight/8 + 80, kScreenWidth, 500)];
    [self.view addSubview:_dataFailView];
    [self.dataFailView netRequestFailWithBlock:^{
        [self setUpData];
        [_dataFailView hidden];
    }];
}

#pragma mark - 刷新
- (void)reloadData:(UITableView *)tableView
{
    [tableView reloadData];
}


#pragma mark - UI布局
- (void)addSubViews
{
    // 1.添加tableView
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 85) style:(UITableViewStyleGrouped)];
    // tableView去除cell之间的线
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    // tableView不反弹
//    self.tableView.bounces = NO;
    // 设置数据源和代理
    _tableView.dataSource = self;
    _tableView.delegate = self;
    
    [self.view addSubview:self.tableView];
}

#pragma mark - tableView代理方法
#pragma mark - 返回分区数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

#pragma mark - 返回分区行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.allDataArray.count;
}

#pragma mark - 返回cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"MyCell";
    KLSGRadioTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[KLSGRadioTableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:identifier];
    }
    // 显示数据
    if (self.allDataArray.count > 0) {
        // 通过下标获取model
        KLSGRadioModel *model = self.allDataArray[indexPath.row];
        // 给model赋值
        cell.model = model;
    }
    
    return cell;
}

#pragma mark - 返回行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}

#pragma mark - 点击cell跳转详情界面
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
    KLSGPlayRadioViewController *playViewController = (KLSGPlayRadioViewController *)appDelegate.playVC;
    // 根据位置得到model
    KLSGRadioModel *model = self.allDataArray[indexPath.row];
    // radioModel数组
    playViewController.radioModelArray = self.allDataArray;
    // 电台标题
    playViewController.rname = model.rname;
    // 获取当前点击下标
    playViewController.index = indexPath.row;
    playViewController.radioId = model.radioId;
    playViewController.type = VoiceTypeRadio;
    [self presentViewController:playViewController animated:YES completion:nil];
}

#pragma mark - 设置分区表头高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return kScreenWidth/8 + 40*2;
}

#pragma mark - 分区表头添加视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] init];
    //    view.backgroundColor = [UIColor magentaColor];
    for (int i = 0; i < 4; i++) {
        // 1.电台button
        UIButton *radioButton = [[UIButton alloc] initWithFrame:CGRectMake(i * kScreenWidth/4, 40, kScreenWidth/4, kScreenWidth/4/2)];
        radioButton.backgroundColor = [UIColor whiteColor];
        // 设置tag值
        radioButton.tag = i;
        // 给button添加点击方法
        [radioButton addTarget:self action:@selector(actionButton:) forControlEvents:(UIControlEventTouchUpInside)];
        // Button标题
        NSArray *titleArray = @[@"北京台", @"省市台", @"国家台", @"网络台"];
        [radioButton setTitle:titleArray[i] forState:(UIControlStateNormal)];
        [radioButton setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
        [view addSubview:radioButton];
        
        // 3.分割线
        if (i < 3) {
            
            UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(kScreenWidth/4-1, 4, 1, kScreenWidth/8 -4*2)];
            lineView.backgroundColor = [UIColor lightGrayColor];
            [radioButton addSubview:lineView];
        }
        
        
    }
    
    // 4.地区
    UIImageView *areaImage = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, 30, 30)];
    //    areaImage.backgroundColor = [UIColor redColor];
    areaImage.image = [UIImage imageNamed:@"diqu"];
    UILabel *areaLabel = [[UILabel alloc] initWithFrame:CGRectMake(42, 0, 60, 40)];
    areaLabel.text = @"地区";
    //    areaLabel.backgroundColor = [UIColor greenColor];
    areaLabel.textAlignment = YES;
    [view addSubview:areaImage];
    [view addSubview:areaLabel];
    
    // 5.排行榜
    UIImageView *rankImage = [[UIImageView alloc] initWithFrame:CGRectMake(5, kScreenWidth/8 + 45, 30, 30)];
    rankImage.image = [UIImage imageNamed:@"rank"];
    //    rankImage.backgroundColor = [UIColor redColor];
    UILabel *rankLabel = [[UILabel alloc] initWithFrame:CGRectMake(42, kScreenWidth/8 + 40, 60, 40)];
    rankLabel.text = @"排行榜";
    //    rankLabel.backgroundColor = [UIColor greenColor];
    rankLabel.textAlignment = YES;
    [view addSubview:rankImage];
    [view addSubview:rankLabel];
    
    return view;
}

#pragma mark - 电台button点击方法
- (void)actionButton:(UIButton *)radioButton
{
    KLSGRadioListViewController *radioListVC = [[KLSGRadioListViewController alloc] init];
    KLSGCityListViewController *cityListVC = [[KLSGCityListViewController alloc] init];
    
    radioListVC.buttonTag = radioButton.tag;
    
    NSArray *titleArray = @[@"北京台", @"省市台", @"国家台", @"网络台"];
    radioListVC.title = titleArray[radioButton.tag];
    
    if (radioButton.tag == 1) {
        radioListVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:cityListVC animated:YES];
    } else {
        cityListVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:radioListVC animated:YES];
    }
}

#pragma mark - 延迟加载
- (NSMutableArray *)allDataArray
{
    if (!_allDataArray) {
        _allDataArray = [NSMutableArray array];
    }
    return _allDataArray;
}

- (KLSGDataFail *)dataFailView
{
    if (!_dataFailView) {
        _dataFailView = [[KLSGDataFail alloc] init];
    }
    return _dataFailView;
}







- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
